// TaskFunctions.cpp

#include <string>
#include "TaskFunction.h"
#include "taskStorage.h"


TaskFunction::TaskFunction(){
	loadFileContent();
}
	
void TaskFunction::loadFileContent() {
	_loadStatus = _userStorage.loadFile(_taskList);
}


void TaskFunction::addTask(std::string taskDesc, int startTime, int endTime, int dd, int mm, int yy){
	Task newTask;
	newTask.setTask(false, taskDesc, startTime, endTime, dd, mm, yy);
	_taskList.push_back(newTask);

	_userStorage.writeFile(_taskList);
	_state.saveState(_taskList);
	return;
}
	
void TaskFunction::deleteTask(int index){
	std::vector<Task>::iterator taskToDelete = indexToIterator(index);
	_taskList.erase(taskToDelete);
		
	_userStorage.writeFile(_taskList);
	_state.saveState(_taskList);
	return;
}

void TaskFunction::editTask(int index, bool status, std::string taskDesc, int startTime, int endTime, int dd, int mm, int yy){
	std::vector<Task>::iterator taskToEdit = indexToIterator(index);
	taskToEdit->setTask(status, taskDesc, startTime, endTime, dd, mm, yy);

	_userStorage.writeFile(_taskList);
	_state.saveState(_taskList);
	return;
}

void TaskFunction::toggleComplete(int index){
	std::vector<Task>::iterator taskToToggle = indexToIterator(index);
	if (taskToToggle->getCompleteStatus()){
		taskToToggle->setCompleteStatus(false);
	}
	else{
		taskToToggle->setCompleteStatus(true);
	}
}

void TaskFunction::getIncompleteTasks(){
	_displayStatus = _filter.search(_taskList, _displayList, _displayIndexList, false);
	_display.displayTasks(_displayList);
}
	
void TaskFunction::getCompleteTasks(){
	_displayStatus = _filter.search(_taskList, _displayList, _displayIndexList, true);
	_display.displayTasks(_displayList);		
}
	
void TaskFunction::searchTasks(std::string searchTerm){
	_displayStatus = _filter.search(_taskList, _displayList, _displayIndexList, searchTerm);
	_display.displayTasks(_displayList);	
}

void TaskFunction::undo(){
	if(_state.undo(_taskList)){
		_userStorage.writeFile(_taskList);
		//_display.something();//confirmation message I haven't coded yet
	}
	else{
		//_display.something();//error message I haven't coded yet
	}
}

void TaskFunction::redo(){
	if(_state.redo(_taskList)){
		_userStorage.writeFile(_taskList);
		//_display.something();//confirmation message I haven't coded yet
	}
	else{
		//_display.something();//error message I haven't coded yet
	}
}

std::vector<Task>::iterator TaskFunction::indexToIterator(int index){
	std::vector<std::vector<Task>::iterator>::iterator iter = _displayIndexList.begin();
	for(int i=1; i!=index; i++){
		iter++;
	}
	return *iter;
}